<?php
class DwController extends ServiceController
{
	public function actions() 
	{
        return array(
            'api'=>array(
                'class'=>'CWebServiceAction',
	        	'classMap'=>array(
					'Job',
                    'Resource',
        			'Task',
				),
            ),
        );
    }
    
	/**
	 * @param string username
	 * @param string password
	 * @return boolean whether login is valid
	 * @soap
	 */
	public function login($username,$password)
	{
		$identity=new UserIdentity($username,$password);
		if($identity->authenticate())
		{
			Yii::app()->user->login($identity);
		}
		return $identity->isAuthenticated;
	}
	
    /**
     * Returns all resource
     * @return Resource[] the resource records 
     * @soap
     */
    public function getResources() 
    {
        return Resource::model()->findAllByAttributes(array('res_type'=>ResourceType::Log));
    }
    
    /**
     * @param Job submit job
     * @return string job no 
     * @soap
     */
    public function submitJob($job) 
    {
        // check the job parameters

		$job->user_id = Yii::app()->user->id;
		$job->job_type = JobType::Query;
		$job->state = JobState::Submit;
		$job->submit_time = date('Y-m-d H:i:s');
		$job->workflow_name = 'AdhocHiveQuery';
		
		$res_id = $job['res_id'];
		$output_name = $job['output_name'];
		$system_id = $job['system_id'];
		
        
        // Get input resource
        $resService = ResourceService::getInstance();
        $resource = $resService->getResourceById($model->res_id); 
        
        // Create output resource
        $outputResource = array(
        	'res_name'	=>	$model->output_name,
        	'product_id'	=>	$resource['product_id'],
        	'res_type'	=>	ResourceType::QueryOutput,
        	'res_frequency'	=>	$resource['res_frequency'],
        	'quality_level'	=>	$resource['quality_level'],
        );
		$outputResId = $resService->addOutputResource($outputResource);
		if($outputResId === false) {
			 Yii::log("can't add output resource for [{$model->output_name}]", CLogger::LEVEL_ERROR, FRONTEND_LOG);
			return false;
		}	
        
        $outputResource['res_id'] = $outputResId;
        $jobParams = array(
            'inputs'    =>  array(
                array(
                	'resource'	=>	$resource,
                    'filter'	=>	array(
                        'select'	=>	array(
                            'tv_sec'	=>	array('type'=>'int', 'length'=>4),
                            'mid'	=>	array('type'=>'string', 'length'=>32),
                            'ip'	=>	array('type'=>'string', 'length'=>20),
                            'path'	=>	array('type'=>'string', 'length'=>1024),
                            'level'	=>	array('type'=>'int', 'length'=>4),
                        ),
                        'condition'	=>	$job['query_condition'],
                    ),
                ),
        	),
            'outputs'   =>  array(
                array(
                	'resource'	=>	$outputResource,
                	'system_id'	=>	$model->system_id,
                ),
        	),
        );
        $model->job_param = CJSON::encode($jobParams);    
        $status = $model->save();    
		if($status) {
			$status = Resource::model()->updateByPk($outputResId, array('job_id'	=>	$model->job_id));
		}
		return $status;
    }
    
	/**
	 * Returns the current user job list
     * @return Job[] the job records
     * @soap
     */
    public function getJobs() 
    {       
       return Job::model()->findAllByAttributes(array('user_id'=>Yii::app()->user->id));
    }
    
	/**
	 * Returns the current user task list
     * @return Task[] the task records
     * @soap
     */
    public function getTasks() 
    {       
        return Task::model()->with('job')->findAll(array(
            'condition' =>  'job.user_id=:user_id',
            'params'    =>  array(':user_id' => Yii::app()->user->id),
        ));
    }
    
	/**
	 * @param int job id
	 * @return Task[] the task records of job 
	 * @soap
	 */
    public function getTasksByJobId($job_id) 
    {
    	return Task::model()->findAllByAttributes(array('job_id'=>$job_id));
    }
    
	/**
	 * @param int task id
	 * @return Task task
	 * @soap
	 */
    public function getTask($task_id)
    {
    	return  Task::model()->findByPk($task_id);
    }
    
    /**
	 * @param int task id
	 * @return array task execution state
	 * @soap
	 */
    public function getState($task_id)
    {
    	$task = Task::model()->findByPk($task_id, array(
    		'select'=>'state'
    	));
    	return array(
    		'state' => $task->state,
    		'message'	=>	$task->detail,
    	);
    }
    
	/**
	 * This action serves as a SOAP client to test the phonebook Web service.
	 */
	public function actionTest()
	{
        ini_set ( 'soap.wsdl_cache_enable' , 0 ); 
        ini_set ( 'soap.wsdl_cache_ttl' , 0 );
		$wsdlUrl=Yii::app()->request->hostInfo.$this->createUrl('dw/api');
		$client=new SoapClient($wsdlUrl);
		echo "<pre>";
		echo "login...\n";
		$client->login('abc','abc');
		echo "\nsubmit a new job...\n";
		$job = new Job;
		$job->job_name = "test";
		print_r($client->submitJob($job));
        echo "\nget all resources...\n";
        print_r($client->getResources());
        echo "\nget tasks\n";
        print_r($client->getTasksByJobId(1));
        print_r($client->getTasks());
        echo "\nget task state\n";
        print_r($client->getState(12));
		echo "\ndone\n\n";
		echo "</pre>";
	}
}
